/*cardDoctorAdmin - services.js - Yadong Zhu 2014*/
(function() {
    'use strict';
    /* Services */
    var env = '';
    // env = 'http://10.128.139.35:8080/brackets'; //dev
    angular.module('cardDoctorAdmin.services', ['ngResource'])
        .factory('cardDoctorAdminService', function($resource, $http) {
            return $resource('/cardDoctor/admin/:action/:param1/:param2', {
                action: '@action',
                param1:'@id'
            }, {
                search: {
                    method: 'GET',
                    headers: {
                        'Accept': 'application/json'
                    },
                    params: {
                        action: 'listCards'
                    },
                    // isArray: true,
                    withCredentials: true
                },
                getCard: {
                    method: 'GET',
                    headers: {
                        'Accept': 'application/json'
                    },
                    params: {
                        action: 'base',
                        param1:'@id'
                    },
                    withCredentials: true
                },
                save: {
                    method: 'POST',
                    headers: {
                        'Accept': 'application/json'
                    },
                    params: {
                        action: 'saveCard'
                    },
                    withCredentials: true
                },
            });
        })
        .service('uuid4', function() {
            var fmt = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';
            this.generate = function() {
                return fmt.replace(/[xy]/g, function(c) {
                    var r = Math.random() * 16 | 0, // inclusive or, 10000 | 00000
                        v = c === 'x' ? r : (r & 0x3 | 0x8);
                    return v.toString(16);
                });
            };
        })
.service('loginService', ['$resource', 
  function($resource){
 return $resource('/admin/:action',
   {
    action: '@action'
   },
  {
    login: { 
     method: 'POST',
     headers: {'Accept': 'application/json'},
     params: {action:"login"}
   },
    logout: { 
     method: 'GET',
     params: {action:"logout"}
   }
 });
}])
        .service('cardDoctorCacheService', ['$routeParams', '$cacheFactory', '$q', 'cardDoctorAdminService',
            function($routeParams, $cacheFactory, $q, cardDoctorAdminService) {
                var cache = $cacheFactory('cardDoctorAdminService');
                return {
                    getCard: function() {
                    
                        return null;
                    },
                    search: function(query,cachedContent) {
                        cachedContent=angular.isUndefined(cachedContent)?false:cachedContent;
                        var cacheString = JSON.stringify(query);
                        var results = cache.get('search for:' + cacheString);
                        if (!results||!cachedContent) {
                            results = cardDoctorAdminService.search(query);
                            cache.put('search:' + cacheString, results);
                            //TODO if a user adds a game clear this.  
                        }
                        return results;
                    }
                };
            }
        ])
      // extend the implementation of location so that we have the option to skip the page reload when moving from new to edit
    // this should make a faster and lighter weight page for users since the template and data will not be re-requested.
    //use $injector to get $route to prevent from sending a request when loading the service, which causes unit test failing
    .factory('location', [
        '$location',
        '$injector',
        '$rootScope',
        function($location, $injector, $rootScope) {
            $location.skipReload = function() {
                var $route = $injector.get("$route");
                var lastRoute = $route.current;
                var un = $rootScope.$on('$locationChangeSuccess', function() {
                    $route.current = lastRoute;
                    un();
                });
                return $location;
            };
            return $location;
        }
    ])
    ;
}());

function getDatetimeString(d){//yyyy-mm-ddThh:mm
    var y=d.getFullYear();
    var m=(d.getMonth()<9)?"0"+(d.getMonth()+1):(d.getMonth()+1);
    var da=(d.getDate()<10)?"0"+d.getDate():d.getDate();
    var h=(d.getHours()<10)?"0"+d.getHours():d.getHours();
    var mm=(d.getMinutes()<10)?"0"+d.getMinutes():d.getMinutes();
    return y+"-"+m+"-"+da+"T"+h+":"+mm;
}
